package currentment;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

class Foo2 {
    // 锁
    private Lock lock;
    // 输出顺序
    private int index;
    private Condition condition;


    public Foo2() {
        lock = new ReentrantLock();
        index = 1;
        condition = lock.newCondition();
    }

    public void first(Runnable printFirst) throws InterruptedException {
        lock.lock();
        try {
            while (index != 1) {
                condition.await();
            }
            printFirst.run();
            index ++;
            condition.signalAll();
        } catch (Exception e) {
            e.printStackTrace();
        }
        lock.unlock();
    }

    public void second(Runnable printSecond) throws InterruptedException {
        lock.lock();
        try {
            while (index != 2) {
                condition.await();
            }

            printSecond.run();
            index ++;
            condition.signalAll();
        } catch (Exception e) {
            e.printStackTrace();
        }
        lock.unlock();
    }

    public void third(Runnable printThird) throws InterruptedException {
        lock.lock();
        try {
            while (index != 3) {
                condition.await();
            }
            printThird.run();
            index ++;
            condition.signalAll();
        } catch (Exception e) {
            e.printStackTrace();
        }
        lock.unlock();
    }
}